﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections.Generic;

using Relocation.Com;
using Relocation.Data;
using Relocation.Base;
using Relocation.Controls;
using Relocation.Com.Tools;
using Relocation.Forms.Window;

using FarsiLibrary.Win;
using Relocation.UI.Interface;
using Relocation.Base.UI;



namespace Relocation.UI
{
	public partial class MainWindow : BaseForm
	{
		/// <summary>
		/// 判断选项卡是否是切换
		/// </summary>
		public bool isTabChange = false;

		#region 构造函数

		public MainWindow()
			: base()
		{
			InitializeComponent();
			Initialize();
		}

		public MainWindow(Session session)
			: base(session)
		{
			InitializeComponent();
			Initialize();
		}
		#endregion


		/// <summary>
		/// 初始化方法
		/// </summary>
		private void Initialize()
		{
			ControlTag tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN));
			this.userManager.Tag = tag;
			this.Restores.Tag = tag;
			this.Backups.Tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR));
		}

		private void MainWindow_Load(object sender, EventArgs e)
		{			
			object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
			if (attributes.Length > 0)
			{
				this.Text = ((AssemblyProductAttribute)attributes[0]).Product;
			}
			loginLoad();    //登录初始化 					
		}

		#region 标签控件相关方法
		/// <summary>
		/// 将窗体显示在标签里
		/// </summary>
		/// <param name="form">需要显示的窗体</param>
		public void showForm(Form form)
		{
			try
			{
				foreach (FATabStripItem item in this.faTabStrip.Items)
				{
					if (item.Title == form.Text)
					{
						isTabChange = true;
						this.faTabStrip.SelectedItem = item;
						isTabChange = false;
						return;
					}
				}
				form.Dock = DockStyle.Fill;
				form.FormBorderStyle = FormBorderStyle.None;
				form.TopLevel = false;
				isTabChange = false;
				this.faTabStrip.AddTab(new FATabStripItem(form.Text, form), true);
				isTabChange = true;
				form.Show();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				Debug.WriteLine(ex);
				throw;
			}

		}

		/// <summary>
		/// 标签切换事件
		/// </summary>		
		private void faTabStrip_TabStripItemSelectionChanged(TabStripItemChangedEventArgs e)
		{
			if (e.ChangeType == FATabStripItemChangeTypes.SelectionChanged)
			{
				if (isTabChange)
				{
					if (e.Item.Controls.Count > 0)
					{
						e.Item.Controls[0].Refresh();
						e.Item.Controls[0].Focus();
					}
				}
			}
		}

		/// <summary>
		/// Fas the tab strip_ tab strip item closing.
		/// </summary>		
		private void faTabStrip_TabStripItemClosing(TabStripItemClosingEventArgs e)
		{
			if (e.Item.Title == "快速搜索")
			{
				e.Cancel = true;
				return;
			}
			if (this.faTabStrip.Items.Count > 1)
			{
				Form form = e.Item.Controls[0] as Form;
				if (form != null)
				{
					form.Close();
				}
			} else
			{
				e.Cancel = true;
			}
		}

		#endregion

		#region 数据库备份与恢复

		/// <summary>
		/// 数据库还原
		/// </summary>		
		private void DataRestore_Click(object sender, EventArgs e)
		{
			try
			{
				string DefaultDirectory = Tools.GetStartupPath() + @"\DataBackup\";
				if (!Directory.Exists(DefaultDirectory))
					Directory.CreateDirectory(DefaultDirectory);

				OpenFileDialog open = new OpenFileDialog();
				open.Title = "请选择数据库的备份文件";
				open.AddExtension = true;
				open.CheckPathExists = true;
				open.Filter = "数据库备份文件 (*.bak)|*.bak";
				open.FilterIndex = 0;
				open.Multiselect = false;
				open.InitialDirectory = DefaultDirectory;
				DialogResult dialogResult = open.ShowDialog();
				if (!dialogResult.Equals(DialogResult.OK))
					return;

				if (!MyMessagebox.Confirm("自上次备份以来的所有数据将丢失,是否继续?").Equals(DialogResult.Yes))
					return;

				string fileName = open.FileName;
				Tools.DataRestore(fileName);
				MyMessagebox.Show("恢复成功，请重新打开本系统！");
			} catch (Exception)
			{
				string error = "还原数据库时发生错误，请重新打开本系统！";
				Log.Error(error);
				MyMessagebox.Error(error);
			}
			Application.Exit();
		}

		/// <summary>
		/// 数据库备份
		/// </summary>
		private void DataBackup_Click(object sender, EventArgs e)
		{
			try
			{
				string DefaultDirectory = Tools.GetStartupPath() + @"\DataBackup\";
				if (!Directory.Exists(DefaultDirectory))
					Directory.CreateDirectory(DefaultDirectory);

				SaveFileDialog save = new SaveFileDialog();
				save.Title = "请选您要保存备份文件的位置";
				save.DefaultExt = ".bak";
				save.AddExtension = true;
				save.CheckPathExists = true;
				save.Filter = "数据库备份文件 (*.bak)|*.bak";
				save.FilterIndex = 0;
				save.InitialDirectory = DefaultDirectory;
				save.FileName = DefaultDirectory + System.DateTime.Now.ToLongDateString() + ".bak";
				DialogResult dialogResult = save.ShowDialog();
				if (!dialogResult.Equals(DialogResult.OK))
					return;

				string fileName = save.FileName;

				if (System.IO.File.Exists(fileName))
					System.IO.File.Delete(fileName);
				//先备份到临时文件，然后拷贝到对应目录（原因：数据库的角色对磁盘的访问权限较低，经常创建文件时提示“拒绝访问！”）
				string tempFileName = Tools.GetStartupPath() + @"\" + DateTime.Now.ToFileTime().ToString();
				Tools.DataBackup(tempFileName);
				System.IO.File.Move(tempFileName, fileName);
				MyMessagebox.Show("备份成功！");
				return;
			} catch (Exception)
			{
				string error = "备份时发生错误！";
				Log.Error(error);
				MyMessagebox.Error(error);
			}
		}

		#endregion

		#region 菜单按钮事件
		private void modifyPassword_Click(object sender, EventArgs e)
		{
			using (PwdEdit pwdModify = new PwdEdit(Session))
			{
				pwdModify.ShowDialog();
			}
		}

		/// <summary>
		/// 显示UserList
		/// </summary>		
		private void userManager_Click(object sender, EventArgs e)
		{
			showForm(new UserList(Session));
		}

		/// <summary>
		/// 显示ProSearchList
		/// </summary>		
		private void pro_ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			showForm(new ProjectList(Session));
		}

		/// <summary>
		/// 显示RelocateesView
		/// </summary>		
		private void relocateesList_Click(object sender, EventArgs e)
		{
			showForm(new RelocateesList(Session));
		}

		/// <summary>
		/// 显示statistics
		/// </summary>		
		private void toolStripMenuItem3_Click(object sender, EventArgs e)   //数据统计
		{
			showForm(new statistics(Session));
		}

		/// <summary>
		/// 程序退出
		/// </summary>		
		private void exitWindow_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		/// <summary>
		/// 显示AboutBox
		/// </summary>		
		private void AboutBox_Click(object sender, EventArgs e)
		{
			using (AboutBox aboutBox = new AboutBox())
			{
				aboutBox.ShowDialog();
			}
		}

		/// <summary>
		///  显示HousesList
		/// </summary>
		private void HousesManager_Click(object sender, EventArgs e)
		{
			try
			{
				showForm(new HousesList(Session));
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error(ex.Message);
			}
		}

		/// <summary>
		/// 切换项目
		/// </summary>		
		public void ProChoose_ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (this.Session.GetMainTreeView().IsRefreshIng)
			{
				MyMessagebox.Show("菜单正在刷新，请稍候...");
				return;
			}

			Project project = this.GetProject();
			if (project == null || project.project_id.Equals(this.Session.Project.project_id))
				return;
			this.InitProject(project);
		}

		/// <summary>
		/// 显示帮助
		/// </summary>		
		private void menuHelp_Click(object sender, EventArgs e)
		{
			try
			{
				string helpFile = @"操作手册.doc";
				if (System.IO.File.Exists(helpFile))
				{
					Process.Start(helpFile);
				} else
				{
					MyMessagebox.Show(@"对不起，未找到帮助文件（" + helpFile + "）！");
				}

			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Error("操作手册打开失败！");
			}
		}

		/// <summary>
		/// 切换用户
		/// </summary>		
		private void SwitchUser_Click(object sender, EventArgs e)
		{
			User user = this.GetUser();
			if (user == null)
				return;
			this.Session.User = user;
			loginLoad();
		}

		private void InitUser(User user)
		{
			this.Session.User = user;
			this.CurrentlyUser.Text = user.name;
			this.InitControlsRole();
			
		}

		/// <summary>
		/// 显示快速搜索
		/// </summary>		
		private void QuickSearch_Click(object sender, EventArgs e)
		{
			foreach (FATabStripItem item in this.faTabStrip.Items)
			{
				if (item.Title == "快速搜索")
				{
					isTabChange = true;
					this.faTabStrip.SelectedItem = item;
					isTabChange = false;
					return;
				}
			}
			this.CreateMainTreeView(this.Session);
		}

		#endregion


		#region 其他方法

		/// <summary>
		/// 登录初始化
		/// </summary>		
		public void loginLoad()
		{
			this.InitUser(this.Session.User);
			Project project = this.GetProject();
			if (project == null)
			{
				Application.Exit();
				return;
			}
			this.InitProject(project);
		}

		private void InitProject(Project project)
		{
			this.Session.Project = project;
			this.CurrentlyPro.Text = Session.Project.name;
			//关闭所有选项卡
			while (this.faTabStrip.Items.Count > 0)
				this.faTabStrip.RemoveTab(this.faTabStrip.Items[0]);
			this.CreateMainTreeView(this.Session);
		}

		private void CreateMainTreeView(Session session)
		{
			MainTreeView mainTreeView = new MainTreeView(session);
			mainTreeView.Dock = DockStyle.Fill;
			this.faTabStrip.AddTab(new FATabStripItem("快速搜索", mainTreeView), true);
			this.Session.DataRefresh = true;
			mainTreeView.Refresh();
			session.SetMainTreeView(mainTreeView);
		}

		/// <summary>
		/// 获得程序当前的路径
		/// 此方法的主要目的是为了去除路径字符中最后一个反斜杠（如果盘符下根目录的话会出现自动增加反斜杠的情况）
		/// </summary>
		/// <returns>程序当前的路径</returns>
		public string GetStartupPath()
		{
			if (!Application.StartupPath.EndsWith(@"\"))
			{
				return Application.StartupPath;
			} else
			{
				return Application.StartupPath.Remove(Application.StartupPath.Length - 1, 1);
			}

		}
		#endregion

		/// <summary>
		/// 打印功能
		/// </summary>		
		private void toolStripMenuItem3_Click_1(object sender, EventArgs e)
		{
			try
			{
				if (this.faTabStrip.SelectedItem.Controls.Count > 0)
				{
					IPrintForm iPringForm = this.faTabStrip.SelectedItem.Controls[0] as IPrintForm;
					if (iPringForm == null)
					{
						MyMessagebox.Show("该页面暂无导出功能!");
						return;
					}
					iPringForm.Print();
				}
			} catch (Exception ex)
			{
				Log.Error(ex);
				MyMessagebox.Show("操作失败！");
			}
		}


		private void 修复数据状态ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			WaitForm waitForm = new WaitForm("请等待", "正在更新数据库信息，请稍候...");
			ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) {
				try
				{
					this.Session.DataModel.RepairState();
					this.Invoke(new MethodInvoker(delegate() {
						DialogResult dialogResult = MyMessagebox.Confirm("建议您重新运行此程序，是否立即关闭？");
						if (dialogResult.Equals(DialogResult.Yes))
							Application.Exit();
						else
							waitForm.CloseForm();
					}));
				} catch (Exception ex)
				{
					Log.Error(Tools.GetExceptionMessage(ex));
					MyMessagebox.Error(Tools.GetExceptionMessage(ex));
					this.Invoke(new MethodInvoker(delegate() {
						waitForm.CloseForm();
					}));
				}
			}));
			waitForm.ShowDialog();
		}

		private void 村别管理ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			VillagesList VillagesList = new VillagesList(this.Session);
			showForm(VillagesList);
		}

		private void toolStripMenuItem5_Click(object sender, EventArgs e)
		{
			//SendSuggest SendSuggest = new SendSuggest();
			//SendSuggest.ShowDialog();
		}

		private void toolStripMenuItem6_Click(object sender, EventArgs e)
		{
			try
			{
				Process.Start("tencent://message/?uin=1479447921&Menu=yes");
			} catch (Exception ex)
			{
				Log.Error(Tools.GetExceptionMessage(ex));
			}
		}

		private void 规划红线图ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				using (ProjectPic ProjectPic = new ProjectPic(this.Session, this.Session.Project))
				{
					ProjectPic.ShowDialog();
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}
		}

		private void 清理文件ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				string dir = Tools.GetStartupPath() + @"\docs\";

				string[] files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories);
				List<string> AllFilesPath = this.Session.DataModel.GetAllFilesPath();
				foreach (string file in files)
				{
					if (!AllFilesPath.Contains(file))
					{
						Tools.DeleteFile_Directory(file);
					}
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
			}
		}



		private void 数据统计ToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			showForm(new VillagesStatistics(this.Session));
		}
		/// <summary>
		/// 选择sql脚本更新数据库的按钮
		/// </summary>		
		private void toolStripMenuItemUpdateDataBase_Click(object sender, EventArgs e)
		{
			if (!MyMessagebox.Confirm("此操作仅供专业人员操作，确定要继续吗？").Equals(DialogResult.Yes))
				return;
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Title = "请选择数据库的备份文件";
			openFileDialog.AddExtension = true;
			openFileDialog.CheckPathExists = true;
			openFileDialog.Filter = "SQL脚本文件 (*.sql)|*.sql";
			openFileDialog.FilterIndex = 0;
			openFileDialog.Multiselect = false;
			DialogResult dialogResult = openFileDialog.ShowDialog();
			if (!dialogResult.Equals(DialogResult.OK))
				return;

			string fileName = openFileDialog.FileName;
			try
			{
				Tools.ExecSqlFile(fileName);
				MyMessagebox.Show("执行成功");
			} catch (Exception ex)
			{
				string error = Tools.GetExceptionMessage(ex);
				Log.Error(error);
				MyMessagebox.Show(error);
			}
		}

		private User GetUser()
		{
			try
			{
				using (LoginForm login = new LoginForm(Session))
				{
					if (login.ShowDialog(this).Equals(DialogResult.OK) || login.User != null)
					{
						return login.User;
					}
					return null;
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				return null;
			}
		}


		private Project GetProject()
		{
			try
			{
				int projectCount = this.Session.DataModel.Projects.Count();
				if (projectCount < 1)
				{
					using (ProjectsWindow projectWindow = new ProjectsWindow(this.Session))
					{
						return projectWindow.ShowDialog(this).IsOK() ? projectWindow.Project : null;
					}
				} else
				{
					using (ProjectSelect projectSelect = new ProjectSelect(this.Session))
					{
						return projectSelect.ShowDialog(this).IsOK() ? projectSelect.Project : null;
					}
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				this.MessageBoxShowInfo("操作失败！");
			}
			return null;

		}

	}
}
